local qulao = fk.CreateSkill {
  name = "inker_qulao",
}

qulao:addEffect(fk.AfterCardsMove, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    local num = 0
    if not player:hasSkill(self.name) then return false end
    for _, move in ipairs(data) do
      if move.toArea ~= Card.Processing and move.skillName ~= qulao.name and
        not table.contains({fk.ReasonUse, fk.ReasonResponse}, move.moveReason) then
        for _, info in ipairs(move.moveInfo) do
          local room = player.room
          local cid = info.cardId
          if room:getCardOwner(cid) ~= player then
            if move.from == player then
              if info.fromArea == Card.PlayerHand then
                num = num + 1
              end
            elseif info.fromArea == Card.Processing then
              room.logic:getEventsByRule(GameEvent.MoveCards, 1, function(e)
                for _, e_move in ipairs(e.data) do
                  if e_move.toArea == Card.Processing then
                    for _, e_info in ipairs(e_move.moveInfo) do
                      if e_info.cardId == cid and e_info.fromArea ~= Card.Processing then
                        if e_info.fromArea == Card.PlayerHand and e_move.from == player then
                          num = num + 1
                        end
                        return true
                      end
                    end
                  end
                end
              end, 0)
            end
          end
        end
      end
    end

    if num > 0 then
      event:setSkillData(self, "inker_qulao_num", num)
      return true
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local num = event:getSkillData(self, "inker_qulao_num") or 0
    local total_num = num
    if num == 0 then return false end
    local max_card_num = 0
    for _, p in ipairs(room:getAlivePlayers(false)) do
      max_card_num = math.max(max_card_num, #p:getCardIds("he"))
    end

    local _, ret = room:askToUseActiveSkill(player, {
      skill_name = "#inker_qulao_active",
      prompt = "#inker_qulao-invoke:::" .. 0 .. ":" .. num,
      cancelable = true,
      extra_data = {
        skillName = qulao.name,
        num = num,
        max_num = math.min(num, max_card_num),
        current_num = 0,
        skill_targets = {},
      },
    })
    if not ret then return end
    if #ret.targets > 0 then
      local skill_num = ret.interaction
      local targets = {}
      local ui_strings = {}
      local tos = {}
      for _, p in ipairs(ret.targets) do
        table.insert(tos, p)
        targets[p] = skill_num
        ui_strings[tostring(p.id)] = skill_num
        total_num = total_num - skill_num
      end
      while total_num > 0 do
        local _, next_ret = room:askToUseActiveSkill(player, {
          skill_name = "#inker_qulao_active",
          prompt = "#inker_qulao-invoked:::" .. (num - total_num) .. ":" .. num,
          cancelable = true,
          extra_data = {
            skillName = qulao.name,
            num = num,
            max_num = math.min(total_num, max_card_num),
            current_num = num - total_num,
            skill_targets = ui_strings,
          },
        })
        if next_ret then
          local next_skill_num = next_ret.interaction
          for _, p in ipairs(next_ret.targets) do
            if not targets[p] then
              table.insert(tos, p)
              targets[p] = next_skill_num
            else
              targets[p] = (targets[p] or 0) + next_skill_num
            end
            ui_strings[tostring(p.id)] = targets[p]
            total_num = total_num - next_skill_num
          end
        else break
        end
      end
      room:sortByAction(tos)
      event:setCostData(self, {  history_branch = "recast", tos = tos, skill_data = targets })
      return true
    else
      event:setCostData(self, { history_branch = "guanxing", num = num })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local dat = event:getCostData(self)
    if dat.history_branch == "guanxing" then
      local num = dat.num or 0
      if num == 0 then return end
      room:askToGuanxing(player, {
        cards = table.connect(room:getNCards(num), room:getNCards(num, "bottom")),
        skill_name = qulao.name,
        top_limit = {num, num},
        bottom_limit = {num, num},
      })
    elseif dat.history_branch == "recast" then
      local skill_data = dat.skill_data or {}
      local cards = {}
      for _, p in ipairs(dat.tos) do
        local num = skill_data[p] or 0
        if p:isAlive() and num > 0 then
          cards[p] = room:askToChooseCards(player, {
            min = num,
            max = num,
            target = p,
            flag = "he",
            skill_name = qulao.name,
            prompt = "#inker_qulao-recast:" .. p.id .. "::" .. num,
          })
        end
      end
      for _, p in ipairs(dat.tos) do
        room:recastCard(cards[p], p, qulao.name)
      end
    end
  end
})

Fk:loadTranslationTable{
  ["inker_qulao"] = "劬劳",
  [":inker_qulao"] = "当你不以此法且非使用或打出而<a href = 'inker_qulao_lost_handcard'>失去手牌</a>后，可以选择一项：<br>" ..
  "1.观看牌堆两端各等量张牌并以任意顺序放回；<br>" ..
  "2.为所有角色重铸共计至多等量张牌。",

  ["inker_qulao_lost_handcard"] = "不算进入处理区，仅计算移动后不在你区域内但最后一次离开时属于你的牌",

  ["#inker_qulao-invoke"] = "劬劳：你可以选择所有角色共计(%arg/%arg2)张牌令它们重铸之，否则你观看牌堆两端各 %arg2 张牌并以任意顺序放回",
  ["#inker_qulao-invoked"] = "劬劳：选择所有角色共计(%arg/%arg2)张牌令它们重铸之",
  ["#inker_qulao-recast"] = "劬劳：请选择 %src 的 %arg 张牌重铸之",

  ["$inker_qulao1"] = "情记三顾之恩，亮必继之以死。",
  ["$inker_qulao2"] = "身负六尺之孤，臣当鞠躬尽瘁。",
}

return qulao